import sys
import time
from PyQt4 import QtCore, QtGui
from ventana import Ui_Form
import threading,  Queue

class WindowChat(threading.Thread):
    def __init__(self,   q,  queueSend,  queueTextRecv):
        threading.Thread.__init__(self)
        self.q = q
        self.queueSend = queueSend
        self.queueTextRecv = queueTextRecv

    def run(self):
        app = QtGui.QApplication(sys.argv)
        window_chat = Window(self.q,  self.queueSend,  self.queueTextRecv)
        window_chat.show()
        app.exec_() 

class Window(QtGui.QDialog):
    def __init__(self,  q,  queueSend,  queueTextRecv):
        QtGui.QDialog.__init__(self)
        self.ui = Ui_Form()
        self.ui.setupUi(self)
        self.q = q
        self._queueSend = queueSend
        self._queueTextRecv = queueTextRecv
        QtCore.QObject.connect(self.ui.text_send,QtCore.SIGNAL("textChanged()"), self.enable_button_send)
        QtCore.QObject.connect(self.ui.button_send,QtCore.SIGNAL("clicked()"), self.button_send_information)
        QtCore.QObject.connect(self.ui.button_send,  QtCore.SIGNAL("clicked_test()"),  self.prueba)
        
        WindowChatConversation = WindowChatTextConversation(self._queueSend,  self.ui,  self._queueTextRecv)
        WindowChatConversation.start()

        
    def enable_button_send(self):
        self.ui.button_send.setEnabled(True)
        
    def prueba(self):
        try:
            textSend = self._queueTextRecv.get(True,  1)
            print textSend
            self.ui.text_conversation.setText(textSend)
        except:
            print "Error"
    
    def button_send_information(self):
#        text = self.ui.text_send.PlainText()
        text = unicode(self.ui.text_send.toPlainText())
        if text <> '':
            text += '\n'
            self.q.put(1)
            self.q.put(text)
            self.ui.text_conversation.setText(text)
        self.ui.text_send.setText('')
        self.ui.button_send.setEnabled(False)
    
    


class WindowChatTextConversation(threading.Thread):
    def __init__(self, queueSend,  ui,  queueTextRecv):
        threading.Thread.__init__(self)
        self._queueSend = queueSend
        self._ui = ui
        self._queueTextRecv = queueTextRecv
    
    def run(self):
        while 1:
            try:
                textSend = self._queueSend.get(True,  1)
#                print textSend
                
            except:
                textSend = ''
            if textSend == 1:
                textSend = self._queueSend.get(True,  1)
                self._queueTextRecv.put(textSend)
#                print textSend
                self._ui.button_send.emit(QtCore.SIGNAL("clicked_test()"))
